
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author xingzhiwen
 * @date 2021/9/14
 * @ddescription:
 */
@SuppressWarnings({"all"})

public class SocketTcp03Server {
    public static void main(String[] args) throws IOException {
        //1.在本机的接口9999端口监听。等待连接
        // 细节是9999端口没有被占用
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端在9999端监听，等待连接");
        //当客户端连接9999端口时，程序会 阻塞，等待连接
        //如果客户端连接，则会返回socket对象，程序继续
        Socket socket = serverSocket.accept();
        System.out.println("socket服务端 = " + socket.getClass());
        //通过socket。getinputstream读取客户端写入到数据通道的数据
        InputStream inputStream = socket.getInputStream();
        //io读 字符流
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String s = bufferedReader.readLine();

        System.out.println(s);

        //获取socket想关联的输出流
        OutputStream outputStream = socket.getOutputStream();

        //使用字符输出流的方式
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("hello return msg");
        //结束标志
        bufferedWriter.newLine();
        //手动刷新
        bufferedWriter.flush();

        //关闭流
        bufferedReader.close();
        bufferedWriter.close();
        socket.close();
        serverSocket.close();

    }
}
